#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'wshu'
"""
    ***********************************
    *  @filename : manage.py
    *  @Author : wshu
    *  @CodeDate : 2020/3/8 22:28
    *  @Software : PyCharm
    ***********************************
"""
import os
import sys
import logging
from importlib import import_module
from db.mysql.INITDB import init_db
# from conf.config import BASEUI
from urls import urls_pattern as urls
# from core import get_files, get_categories, filter_mod

import click
import tornado.log
import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpserver
# from tornado.routing import Router, RuleRouter, PathMatches

# 初始化数据库连接
def initDatabase():
    db_session = init_db()
    if db_session:
        setting = dict(
            manage=dict(db=db_session),
        )
        return setting
PARAMETERS = initDatabase()
# print("数据库: ", PARAMETERS)
# 创建路由表


# 创建服务器
def make_app(debug, configure):
    assert isinstance(urls, (list, tuple)), 'urls must be list or tuple'
    return tornado.httpserver.HTTPServer(CustomApplicationHandlers(debug, urls, configure), xheaders=True)

from db.mysql import User
# 自定义应用
class CustomApplicationHandlers(tornado.web.Application):
    """init application"""
    def __init__(self, debug, urls, configure):
        super(CustomApplicationHandlers, self).__init__(
                handlers=urls,
                ui_modules={},
                debug=debug,
                **configure)
        self.db = PARAMETERS['manage']
        if not self.db.get('db') is None:
            self._DBSession  = self.db.get('db')
            self.session = self._DBSession()

# 这里配置的是日志的路径，配置好后控制台的相应信息就会保存到目标路径中。
# tornado.options.log_file_prefix = os.path.join(os.path.dirname(__file__), 'logs/system.log')

# 格式化日志输出格式
# 格式化形式：[2016-08-07 09:38:01 执行文件名:执行函数名:执行行数 日志等级] 内容消息
class InitLogFormat(tornado.log.LogFormatter):
    def __init__(self):
        super(InitLogFormat, self).__init__(
            fmt='%(color)s[%(asctime)s %(filename)s:%(funcName)s:%(lineno)d %(levelname)s]%(end_color)s %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )


@click.command()
@click.option('--addr', default='localhost', help='Server running address. --addr 0.0.0.0')
@click.option('--port', default=8888, help='Server operation port. --port 8080')
@click.option('--profile', default='hfbase', help='Service configuration. --profile hfbase')
def runserver(addr, port, profile):
    settings = import_module(f'Ui.HFmSetting.setting.{profile}')
    tornado.options.parse_command_line()
    tornado.options = settings
    # 初始化日志
    [i.setFormatter(InitLogFormat()) for i in logging.getLogger().handlers]

    app = make_app(settings.DEBUG, settings.hfconf)
    app.listen(address=addr, port=port)

    sys.stdout.write(f"[*]Starting development server at: http://{addr}:{port}\n"
                     f"[*]Tornado version 6.0, using settings: {profile}\n"
                     f"[*]Quit the server with CONTROL-C.\n")
    tornado.ioloop.IOLoop.current().start()


if __name__ == '__main__':
    current_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.insert(0, current_path)
    runserver()